package com.eati.cm;

import com.eati.cm.model.StoryGenre;
import com.eati.cm.model.StoryWork;
import com.eati.cm.serv.IStoryGenreServ;
import com.eati.cm.serv.IStoryWorkServ;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.TransientPropertyValueException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.function.Executable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.InvalidDataAccessApiUsageException;

import javax.script.Invocable;
import javax.transaction.Transactional;
import java.util.List;

@SpringBootTest
class StoryWorkAndStoryGenre {

	@Autowired
	IStoryGenreServ iStoryGenreServ;

	@Autowired
	IStoryWorkServ iStoryWorkServ;

	@Test
	void contextLoads() {
	}

	@Test
	void findAllStoryWork() throws JsonProcessingException {
		List<StoryWork> res = iStoryWorkServ.findAll();
		System.out.println(new ObjectMapper().writeValueAsString(
				res
		));
	}

	@Test
	void findAllStoryGenre() throws JsonProcessingException {
		List<StoryGenre> res = iStoryGenreServ.findAll();
		for (StoryGenre o: res) {
			for(StoryWork storyWork : o.storyWorkBelongsToList){
				System.out.println(new ObjectMapper().writeValueAsString(
						storyWork
				));
			}
		}
		System.out.println(new ObjectMapper().writeValueAsString(
				res
		));
	}

	//保存与未保存之StoryGenre关系之StoryWord——抛出InvalidDataAccessApiUsageException异常
	@Test
	void saveStoryWorkWithUnsavedGenre_throws() throws InvalidDataAccessApiUsageException{
		StoryWork storyWork = new StoryWork("BAASH WORK",
				new StoryGenre("BAASH GENRE", null));
		Assertions.assertThrows(InvalidDataAccessApiUsageException.class,
				() ->
					iStoryWorkServ.save(storyWork)
				);
	}

	@Test
	void saveAndRemoveStoryGenre() throws JsonProcessingException {
		StoryGenre storyGenre = new StoryGenre("BAASH GENRE", null);
		iStoryGenreServ.save(storyGenre);
		System.out.println(new ObjectMapper().writeValueAsString(
				storyGenre
		));
		iStoryGenreServ.delete(storyGenre);
	}
}
